import React, { Component } from 'react';
import { NavBar, SearchBar } from 'antd-mobile'
import { DeleteOutline } from 'antd-mobile-icons'
import { search } from '../utils/api'

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      num:1,
      list: [],
      searchinput: '',//保存搜索框的值
      //保存搜索历史记录
      searchlist: localStorage.getItem('searchlist') ? JSON.parse(localStorage.getItem('searchlist')) : []
    }
  }
  handleBack() {
    this.props.history.go(-1)
  }

  //回车时获取input框的值
  getValue(e) {
    //回车将数据e添加在searchlist数组中
    let arr = this.state.searchlist
    arr.push(e)
    this.setState({
      searchlist: arr
    }, () => {
      //保存在本地存储，用来渲染最近搜索记录
      localStorage.setItem('searchlist', JSON.stringify(this.state.searchlist))
    })

    search({ searchkey: e, page: 1, count: 6 }).then((res) => {
      if(res.data.list.length === 0){
        this.setState({
          num:0,
          list:[]
        })
      }else {
        this.setState({
        list: res.data.list,
        num:1
      })
      }
      console.log(res.data);
      
    })
  }
  //页面一挂载获取
  componentDidMount() {
  }
  render() {
    return (
      <div>
        <NavBar onBack={() => { this.handleBack() }}>
          搜索
        </NavBar>
        <SearchBar placeholder='请输入内容' showCancelButton={() => true} onSearch={(e) => { this.getValue(e) }} />
        <div className='nearsearch'>
          <div className='title'>
            <span>最近搜素</span>
            <span className='del'><DeleteOutline /></span>
          </div>
          <div className='list'>
            {
              this.state.searchlist.map((item, index) => {
                return <span key={index}>{item}</span>
              })
            }
          </div>
        </div>
        <div className='hotsearch'>
          <div className='title'>
            <span>热门搜索</span>
          </div>
          <div className='list'>
            <span>雅诗兰黛</span>
            <span>兰蔻</span>
            <span>黛珂</span>
            <span>香水</span>
          </div>
        </div>
        <h2>为您找到</h2>

        <div className='searchlist'>
          {
            this.state.list.length > 0  &&
            (
              this.state.list.map((item, index) => {
                return (
                  <div className='list' key={index}>
                    <img src={item.pic} alt="" />
                    <div className='name'>{item.name}</div>
                    <div className='price'>
                      <div className='name'>{item.salesPrice.name}</div>
                      <div className='value'>{item.salesPrice.value}</div>
                    </div>
                   
                  </div>
                )
              }) 
              )
            }
        </div>
            <div className='empty' style={{display:this.state.num === 0 ? 'block' : 'none'}}>未搜索到相关商品</div>
      </div>
    );
  }
}

export default App;